package actions;


import java.io.File;


import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;

public class AudioRecordAct extends DefaultBaseAction implements Action {
	
	
	public AudioRecordAct(ActionFactory factory) {
		super(factory);
	}

	// 產生TargetDataLine類別的變數m_targetdataline
	private TargetDataLine m_targetdataline;
	public static final String cmd="r";
	private final String cmd1="r on";
	private final String cmd2="r off";
	boolean isOn=false;
	

	

	public boolean checkCmd(String cmd) {
		if(cmd.equals(cmd1)){
			isOn=true;
			return true;
		}else if(cmd.equals(cmd2)){
			isOn=false;
			return true;
		}else return false;
	}
	
	public void setHandles(Object... hdls) {
	
	}
	protected Object call0(){
		
		if(isOn){
			try {
				if(isRunning()){
					return "already opened";
				}
				String rs = "success.";
				String Filename = "AudioRecord";
				File m_outputFile = new File(Filename+String.valueOf(System.currentTimeMillis())+".wav");
				// 產生AudioFileFormat.Type類別的變數m_targetType Format格式
				AudioFileFormat.Type m_targetType=AudioFileFormat.Type.AU;
		
				if(m_targetdataline==null){
				// 再來設定和取得音效檔的屬性
				AudioFormat audioFormat = null;
				audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100F,
						8, 1, 1, 44100F, false);
				// 然後透過TargetDataLine介面(繼承自DataLine)與音效卡溝通
				DataLine.Info info = new DataLine.Info(TargetDataLine.class,
						audioFormat);
				m_targetdataline = (TargetDataLine) AudioSystem.getLine(info);
				m_targetdataline.open(audioFormat);// try{ }可能發生例外的敘述
				}
					// 產生AudioInputStream類別的變數m_audioInputStream stream流
					AudioInputStream m_audioInputStream = new AudioInputStream(m_targetdataline);
					m_targetdataline.start();
					AudioSystem.write(m_audioInputStream, m_targetType, m_outputFile);
					return rs;
				} catch (Exception e) {
					if (m_targetdataline != null) {
						m_targetdataline.stop();
						m_targetdataline.close();
					}
					e.printStackTrace();
					return "Record failture";
				}
		}else{
			if(isRunning()){
				stop();
				return "Record stoped";
			}else{
				return "already opened";
			}
		}
	}
	private boolean isRunning(){
		return m_targetdataline==null?false:m_targetdataline.isRunning();
	}
	private void stop(){
		if(m_targetdataline!=null&&m_targetdataline.isRunning()){
			m_targetdataline.stop();
			m_targetdataline.close();
		}
	}
}
